<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/26
 * Time: 13:15
 */

namespace App\Http\Admin\Administration\Models;

use Framework\BaseClass\Http\Model;
use App\Eloquent\Estate\Bill as EloquentBill;
use App\Eloquent\Oa\Company as EloquentCompany;

class Bill extends Model
{
    /**
     * @Author pwj
     * 获取电费账单列表
     * @param $page |分页参数
     * @param $pageSize |分页参数
     * @param array $searchField |所搜条件数组
     * @return mixed
     */
    public function getBillList($page, $pageSize, array $searchField, $searchRaw)
    {

//        $propertyList=EloquentProperty::with('Room.buildingInfo')->toSql();
//        $propertyList=EloquentProperty::with(['Room'=>function($query) {
//            $query->select('id','floor','building_id','room','owner_id')->with(['buildingInfo'=>function($query){
//                $query->select('name','id');
//            },'ownerInfo'=>function($query){
//                $query->select('id','contacts');
//            }]);
//        }])->get();
        $re = EloquentBill::select('oa_company.name as owner', 'estate_bill_electricity_fee.*')->leftJoin('oa_company', 'oa_company.id', '=', 'estate_bill_electricity_fee.oa_company_id')->toSql();
//        $select = "(SELECT `jwk-equ-dev`.estate_bill_electricity_fee.*,
//            `jwk-equ-dev`.room.building_id as building_id,
//            `jwk-equ-dev`.room.floor as floor,
//            `jwk-equ-dev`.room.room,
//            `jwk-equ-dev`.owner.name as owner,
// 	IfNULL((SELECT
// 			building.name
// 		FROM
// 			`jwk-equ-dev`.building
// 		WHERE
// 			`jwk-equ-dev`.building.id = `jwk-equ-dev`.room.building_id),0) AS building
//FROM
//	`jwk-equ-dev`.estate_bill_electricity_fee,`jwk-equ-dev`.room,`jwk-equ-dev`.building,`jwk-equ-dev`.owner where `jwk-equ-dev`.owner.id=`jwk-equ-dev`.estate_bill_electricity_fee.owner_id and `jwk-equ-dev`.room.id=`jwk-equ-dev`.estate_bill_electricity_fee.room_id and `jwk-equ-dev`.building.id=`jwk-equ-dev`.room.building_id and `jwk-equ-dev`.building.zone_id=$currentOperationZoneId) as electricity_bill";
        if ($searchRaw) {
            $billList = \DB::table(\DB::raw("($re) as bill"))->where($searchField)->whereRaw($searchRaw, [':current_time' => time()]);
        } else {
            $billList = \DB::table(\DB::raw("($re) as bill"))->where($searchField);
        }
        $billListCount = $billList->count();
        $billList = $billList->forPage($page, $pageSize)->get();
        foreach ($billList as $k => $v) {
            $v->start_time = date('Y-m-d', $v->start_time);
            $v->end_time = date('Y-m-d', $v->end_time);
            if ($v->payment_time != 0) $v->payment_time = date('Y-m-d', $v->payment_time);
            if (time() > $v->time && $v->amount_received < $v->money) $v->status = 2;
            $v->time = date('Y-m-d', $v->time);
        }
        $data['list'] = $billList;
        $data['pageCurrent'] = $page;
        $data['totalRow'] = $billListCount;
        return $data;
    }

    /**
     * @Author pwj
     * 插入电费账单记录
     * @param $request |必须包含 building,floor,room这三个参数，分别对应room表的building_id,floor，room
     */
    public function insertBill($request)
    {
        $re = EloquentBill::create($request);
        if (isset($re->id)) return 1;
        else return 0;
    }

    /**
     * @Author pwj
     * 获取电费账单的某一记录
     * @param $id |电费账单id
     * @return array
     */
    public function getBillById($id)
    {

        $bill = EloquentBill::find($id);
        if (is_null($bill)) xThrow(ERR_LOGIC_NO_DATA_EXIST);
        return $bill;
    }

    /**
     * @Author pwj
     * 更新电费账单
     * @param $request |必须包含 building,floor,room这三个参数，分别对应room表的building_id,floor，room
     */
    public function updateBill($request)
    {
        return EloquentBill::find($request['id'])->update($request);
    }

    /**
     * @Author pwj
     * 将获取的数据导入数据库
     * @param array $data |通过组件excel获取的数组形式数组
     * pre
     * [
     * ['序号','名字'],
     *[1,"asd"],
     * [2,"asd"]
     * ]
     * pre
     * @return \Illuminate\Http\JsonResponse
     */
    public function importBill($data)
    {
        //
        global $insertData, $error, $err_count, $success_count;
        $time_star = time();
        $insertData = [];
        $error = [];
        $err_count = 0;
        $success_count = 0;
        $modelTitle = ['序号', '单价', '初始度数', '本期度数', '减免单价', '减免数量', '开始时间', '结束时间', "账单截止日期", '账单出账日', '账单类型'];
        $electricityInfo = EloquentBill::all(['oa_company_id', 'current_number', 'id']);
        if ($data[0] === $modelTitle) {
            unset($data[0]);
            //将数据存入待插入数组
            while (list($k, $v) = each($data)) {
                try {
                    if (!$v[0]) continue;
                    if ($v[1] === null || !is_numeric($v[1])) throw new \Exception();
                    if ($v[3] === null || !is_numeric($v[3])) throw new \Exception();
                    if ($v[6] === null || !strtotime($v[6])) throw new \Exception();
                    if ($v[7] === null || !strtotime($v[7])) throw new \Exception();
                    if ($v[8] === null || !strtotime($v[8])) throw new \Exception();
                    if ($v[9] === null || !strtotime($v[9])) throw new \Exception();
                    $row['oa_company_id'] = session('current_operation_company_id');
                    $row['prior_number'] = empty(trim($v[2])) ? $electricityInfo->where('oa_company_id', $row['oa_company_id'])->sortByDesc("id")->pluck('current_number')[0] : trim($v[2]);
                    $row["abatement_unit_price"] = empty($v[4]) ? 0 : trim($v[4]);//减免单价
                    $row["abatement_number"] = empty($v[5]) ? 0 : trim($v[5]);//减免数量
                    if (!is_numeric($row['prior_number'])) throw new \Exception();
                    if (!is_numeric($row["abatement_unit_price"])) throw new \Exception();
                    if (!is_numeric($row["abatement_number"])) throw new \Exception();
                    $row["current_number"] = trim($v[3]);//本期度数
                    $row['start_time'] = strtotime(trim($v[6]));
                    $row['end_time'] = strtotime(trim($v[7])) + 24 * 3600 - 1;
                    $row['time'] = strtotime(trim($v[8])) + 24 * 3600 - 1;
                    $row['billing_date'] = strtotime(trim($v[9]));
                    $row["unit_price"] = trim($v[1]);//单价
                    $row['type'] = trim($v[10]);
                    $row['money'] = ($row['unit_price'] - $row['abatement_unit_price']) * ($row['current_number'] - $row['abatement_number'] - $row["prior_number"]);
                    $insertData[] = $row;
                    $success_count++;
                } catch (\Exception $e) {
                    $err_count++;
                    $error[] = $v[0];
                    \Log::info($e);
                    continue;
                }
            }
            //将待插入数组插入
            foreach (array_chunk($insertData, 1000) as $v) {
                EloquentBill::insert($v);
            }
            return $error;
        } else {
            return xThrow(ERR_HTTP_FILE_UPLOAD_FORMAT);
        }
    }

    public function getCompanyInfo(array $field = ['*'])
    {
        return EloquentCompany::all($field);
    }
}